package edu.pku.sei.autounit.generator;

import java.util.Map;

import edu.pku.sei.autounit.core.Variable;
import edu.pku.sei.autounit.core.VariableFactory;
import edu.pku.sei.autounit.reflect.Constructor;
import edu.pku.sei.autounit.reflect.Type;
import edu.pku.sei.autounit.util.NameFactory;
import edu.pku.sei.autounit.util.Statements;

public class ConstructorInvoke implements Variable{

	private Type type;
	private String name;
	private Variable[] parameters;
	private Constructor constructor;
	public ConstructorInvoke
	(Type type,String name,Constructor con,VariableFactory vf,NameFactory nf) {
		this.type = type;
		this.name = name;
		this.constructor = con;
		Type [] ts = constructor.getParameters();
		this.parameters = new Variable[ts.length];
		for(int i = 0 ;i<ts.length;i++ ){
			parameters[i]=vf.getVariable(ts[i], 
				nf.getName(constructor.getDeclaringClass().getFullName(),
				NameFactory.PARAMETER),vf,nf);
		}
	}

	public Type getType() {
		return type;
	}

	public String getValue() {
		return name;
	}
	
	public Statements getInitCode(Map<String,String> map){
		Statements s = new Statements();

		for(int i=0;i<parameters.length;i++){
			s.merge(parameters[i].getInitCode(map));
		}
		
		if(constructor.hasException()){
			s.insertStatement(type.getName(map)+" "+name+" = null;");
			s.insertStatement("try{");
		}
		
		StringBuffer sb=new StringBuffer();
		if(!constructor.hasException()){
			sb.append(type.getName(map)+" ");
		}
		sb.append(name+" = new ");
		
		sb.append(constructor.getDeclaringClass().getName(map)+"(");
	
		for(Variable v:parameters){
			sb.append(v.getValue()+",");
		}
		
		String temp = sb.toString();
		if(temp.endsWith(","))
			s.insertStatement(temp.substring(0, temp.length()-1)+");");
		else
			s.insertStatement(temp.substring(0, temp.length())+");");
		if(constructor.hasException()){
			s.insertStatement("}catch(Throwable e){");
			s.insertStatement("fail();");
			s.insertStatement("}");
		}
		return s;
	}
}